from django.shortcuts import render, redirect, get_object_or_404, reverse
from django.urls.base import reverse_lazy
from django.views.decorators.http import require_http_methods, require_POST
from django.contrib.auth.decorators import login_required
from django.http.response import JsonResponse
from .models import Blog , BlogCategory, BlogComment
from .forms import BlogForm

# Create your views her
# e.
@require_http_methods(['GET'])
def index(request):
    if request.method == 'GET':
        blogs = Blog.objects.all()
        return render(request, template_name='index.html',context={'blogs':blogs})

def blogDetail(request, blog_id):
    try:
        blog = Blog.objects.get(pk=blog_id)
    except Exception as e:
        blog = None
    return render(request, template_name='blog_detail.html',context={'blog':blog})

# @login_required(login_url='/qiauth/login')
@login_required(login_url=reverse_lazy('qiauth:login'))
@require_http_methods(['GET', 'POST'])
def pub_blog(request):
    if request.method == 'GET':
        categories = BlogCategory.objects.all()
        return render(request, template_name='pub_blog.html', context={'categories':categories})
    else:
        form = BlogForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            category_id  = form.cleaned_data.get('category')
            blog = Blog.objects.create(title=title,content=content,category_id=category_id,author=request.user)
            return JsonResponse({'code':200,'message':'博客发布成功！！！','data':{'blog_id':blog.id}})
        else:
            return JsonResponse({'code':400,'message':'参数错误'})


@require_POST
@login_required()
def pub_comment(request):
    print(request)
    blog_id = request.POST.get('blog_id')
    content = request.POST.get('content')
    BlogComment.objects.create(content=content,blog_id=blog_id,author=request.user)
    return redirect(reverse('blog:blogDetail',kwargs={'blog_id':blog_id}))
